package com.fnzx.controller;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.fnzx.common.enums.ResponseStatusEnum;
import com.fnzx.entity.CooperativeUserEntity;
import com.fnzx.entity.PersonalUserEntity;
import com.fnzx.entity.UserEntity;
import com.fnzx.entity.dto.CoopPersonalRelationDto;
import com.fnzx.entity.dto.CooperativeUserDto;
import com.fnzx.entity.dto.PersonalRelaitonUserDto;
import com.fnzx.entity.vo.CooperativeWithPersonalVo;
import com.fnzx.entity.vo.UserInfoVo;
import com.fnzx.service.CooperativeUserService;
import com.fnzx.service.UserService;
import com.fnzx.util.PageUtils;
import com.fnzx.util.R;
import com.fnzx.util.common.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;


/**
 * 
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2021-10-23 22:20:00
 */
@Api(tags = "合作伙伴用户")
@RestController
@RequestMapping("iot/cooperativeuser")
public class CooperativeUserController {
    @Autowired
    private CooperativeUserService service;

    @Autowired
    private UserService userService;

    @ApiOperation("信息填报|更改信息")
    @PostMapping("/update")
    public R update(@RequestBody CooperativeUserEntity entity){
        if (service.updateById(entity)) {
            return R.ok();
        }else{
            return R.error(ResponseStatusEnum.USER_NOTFOUND.getStatus(),ResponseStatusEnum.USER_NOTFOUND.getMsg());
        }
    }

    @ApiOperation("查询某个合作伙伴用户下属的个人顾问")
    @GetMapping("/listWithPersonal")
    public R listWithPersonal(@RequestParam Long id){
        CooperativeWithPersonalVo result=service.listWithPersonal(id);
        return R.ok().put("data",result);
    }

    @ApiOperation("分页查询合作伙伴用户")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "当前页",paramType = "query",required = true,dataType = "String"),
            @ApiImplicitParam(name = "limit",value = "每页记录数",paramType = "query",required = true,dataType = "String")
    })
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils pg = service.queryPage(params);
        return R.ok().put("page", pg);
    }

    @ApiOperation(value = "注册新的个人用户到某个合作伙伴",notes = "{\n" +
            "\t\"cooperativeUserId\": 2,\n" +
            "\t\"email\": \"2434780193@qq.com\",\n" +
            "\t\"password\": \"123456\",\n" +
            "\t\"personalUserDetails\": {\n" +
            "\t\t\"bmiHistory\": \"sicau\",\n" +
            "\t\t\"brithday\": \"2002-01-20\",\n" +
            "\t\t\"education\": \"本科\",\n" +
            "\t\t\"expertise\": \"?\",\n" +
            "\t\t\"graduatedFrom\": \"?\",\n" +
            "\t\t\"industryExperience\": \"???无\",\n" +
            "\t\t\"major\": \"计算机\",\n" +
            "\t\t\"name\": \"wzf\",\n" +
            "\t\t\"photoUrl\": \"https://bkimg.cdn.bcebos.com/pic/48540923dd54564e9258c86bc2958b82d158ccbfe104?x-bce-process=image/resize,m_lfit,w_536,limit_1/format,f_jpg\",\n" +
            "\t\t\"resumeFileUrl\": \"\",\n" +
            "\t\t\"serviceDirection\": \"\"\n" +
            "\t},\n" +
            "\t\"telephone\": \"132123123\",\n" +
            "\t\"username\": \"wzf123321\"\n" +
            "}")
    @PostMapping("/addPersonalRelation")
    public R addPersonInCooper(@RequestBody CoopPersonalRelationDto relationDto){
        service.addPersonInCooper(relationDto);
        return R.ok();
    }

    @ApiOperation(value = "添加已经存在的个人用户到某个合作伙伴")
    @GetMapping("/addExistPersonInCooper")
    public R addExistPersonInCooper(@RequestParam Long cooperId,
                                    @RequestParam Long personId) {
        service.addExistPersonInCooper(cooperId,personId);
        return R.ok();
    }

    @ApiOperation("获取所有的合作伙伴以及下属的个人顾问")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "当前页",paramType = "query",required = true,dataType = "String"),
            @ApiImplicitParam(name = "limit",value = "每页记录数",paramType = "query",required = true,dataType = "String")
    })
    @GetMapping("/listAllWithPersonalUser")
    public R listAllWithPersonalUser(@RequestParam Map<String,Object> params){
        List<CooperativeWithPersonalVo> result=service.listAllWithPersonalUser(params);
        return R.ok().put("pg",result);
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response){
        //获取需要导出的数据
        List<CooperativeUserEntity> entities = service.list();
        List<CooperativeUserDto> dataList = entities.stream().map(record -> {
            CooperativeUserDto data = new CooperativeUserDto();
            UserEntity byId = userService.getById(record.getId());
            if (byId!=null){
                BeanUtils.copyProperties(record,data);
                BeanUtils.copyProperties(byId, data);
            }
            return data;
        }).collect(Collectors.toList());
        dataList.removeAll(Collections.singleton(null));
        ExcelUtil<CooperativeUserDto> excelUtil = new ExcelUtil<>();
        excelUtil.export("合作伙伴",dataList,response);
    }

    @ApiOperation("导出全部的合作伙伴下属个人顾问Excel")
    @GetMapping("/exportRelation")
    public void exportRelation(HttpServletResponse response){
        HashMap<String, Object> map = new HashMap<>();
        List<CooperativeWithPersonalVo> entities = service.listAllWithPersonalUser(map);

        ArrayList<PersonalRelaitonUserDto> dataList = new ArrayList<>();
        for (CooperativeWithPersonalVo entity : entities) {
            List<UserInfoVo> personalUserEntities = entity.getPersonalUserEntities();
            personalUserEntities.forEach(item->{
                PersonalRelaitonUserDto data = new PersonalRelaitonUserDto();
                HashMap<String, Object> userInfo = item.getUserInfo();
                PersonalUserEntity personalUserEntity = JSON.parseObject(JSON.toJSONString(userInfo), PersonalUserEntity.class);
                BeanUtils.copyProperties(entity,data);
                BeanUtils.copyProperties(personalUserEntity,data);
                data.setCoopName(entity.getName());
                dataList.add(data);
            });
        }
        dataList.removeAll(Collections.singleton(null));
        ExcelUtil<PersonalRelaitonUserDto> excelUtil = new ExcelUtil<>();
        excelUtil.export("合作伙伴下的个人顾问",dataList,response);
    }
}
